package com.wanxing.sellerapp.upload

import android.content.Context
import android.util.Log
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.wanxing.sellerapp.config.AppConfig
import com.wanxing.sellerapp.seller.events.ShowLogEvent
import org.greenrobot.eventbus.EventBus

class AliyunOSS(context: Context) {

    private val TAG = AppConfig.LOGTAG

    private var oss: OSSClient = OSSClient(
        context.applicationContext, AppConfig.OSS_ENDPOINT,
        OSSAuthCredentialsProvider("${AppConfig.DEFAULT_SERVICE_URL}/seller/oss/sts")
    )

    fun upload(objectKey: String, filePath: String): Boolean{
        val bucketName = AppConfig.BUCKET_NAME
        val put = PutObjectRequest(bucketName, objectKey, filePath)
        put.callbackParam = hashMapOf(
            "callbackUrl" to AppConfig.callbackUrl,
            "callbackBody" to "bucket=\${bucket}&object=\${object}&etag=\${etag}"
        )
        return try {
            oss.putObject(put).statusCode == 200
        } catch (e: ServiceException){
            if (e.statusCode == 203) {
                EventBus.getDefault().post(ShowLogEvent("oss重复上传：$filePath", filePath))
                true
            } else {
                EventBus.getDefault().post(ShowLogEvent("oss上传失败：${e.message}", filePath))
                Log.e(TAG, "$filePath 上传失败", e)
                false
            }

        }

    }
}